package m.app.service;

import m.app.model.AppLogin;
import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.base.util.PowerUtil;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdate;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.db.DBManager;
import m.system.util.StringUtil;
import manage.model.AdminLogin;
import manage.service.AdminLoginService;

import java.util.Date;
import java.util.List;

public class AppLoginService extends Service {
    /**
     * 获取key对应的user 没有则返回null
     */
    public UserInfo getUser(String key) throws Exception {
        AppLogin login=ModelQueryList.getModel(AppLogin.class,key,"user.*","user.headImage.*");
        if(null!=login){
            UserInfo user=login.getUser();
            user.setStore(CacheUtil.get(StoreInfo.class,user.getOrgGroup().getOid()));
            return login.getUser();
        }else return null;
    }

    /**
     * 登录并返回user
     */
    public UserInfo userLogin(String key,String username,String password) throws Exception {
        AdminLogin adminLogin=new AdminLogin();
        adminLogin.setUsername(username);
        adminLogin.setPassword(StringUtil.toMD5(password));
        adminLogin=getService(AdminLoginService.class).loginVerification(adminLogin);
        UserInfo u=new UserInfo();
        u.setOid(adminLogin.getOid());
        AppLogin model=ModelQueryList.getModel(AppLogin.class,key,"*");
        if(null==model) {
            model=new AppLogin();
            model.setOid(key);
            model.setUser(u);
            model.setLoginDate(new Date());
            ModelUpdateUtil.insertModel(model);
        }else{
            model.setUser(u);
            model.setLoginDate(new Date());
            ModelUpdateUtil.updateModel(model);
        }
        //清除其他登录人
        ModelQueryList.getModelList(AppLogin.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("user.oid",u.getOid()),
                QueryCondition.not(QueryCondition.eq("oid",model.getOid()))
            )
        ).forEach((item)-> {
            try {
                userLogout(item.getOid());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        //设置session缓存
        PowerUtil.setAppUser(key,u.getOid());
        return getUser(key);
    }
    public void userLogout(String key) throws Exception {
        AppLogin model=ModelQueryList.getModel(AppLogin.class,key,"*");
        if(null!=model) ModelUpdateUtil.deleteModel(model);
        PowerUtil.clearAppUser(key);
    }
}
